
import * as ol from './openLayer'
import { ToolbarControl } from './toobar'
import { defaults as defaultControls } from 'ol/control.js'
import { createLayer } from './layer'
import FullScreen from 'ol/control/FullScreen'
export function initMap(mapObj) {
  const { id, options } = mapObj
  const view = new ol.View({
    projection: options.projection,
    center: options.center,
    zoom: options.zoom,
    maxZoom: options.maxZoom,
    minZoom: options.minZoom
  })
  const map = new ol.Map({
    target: id,
    view: view,
    controls: defaultControls({
      zoom: true,
      rotate: true,
      attribution: true,
    }).extend([
      new FullScreen(),
    ])
  })
  createLayer(map, options.mapLayers)
  if (options.toolbarConfig.show) {
    const toolbarControl = new ToolbarControl(map, options.toolbarConfig)
    map.addControl(toolbarControl)
  }
  const mapview = map.getView(); // 获取地图视图实例

  //监听窗口变化-使得地图能够完全铺满整个容器
  window.addEventListener('resize', function() {
    setTimeout(() => {
      map.updateSize()
      updateImagePosition()
      document.addEventListener('fullscreenchange', updateImagePosition)
      mapview.on('change:resolution', updateImagePosition)
      mapview.on('change:center', updateImagePosition)
    }, 200); // 延迟 200 毫秒
  })

  // 创建并添加图片图层
  const bottomLeftFeature = new ol.Feature(new ol.Point([0, 0]));
  const iconStyle = new ol.Style({
    image: new ol.Icon({
      anchor: [0.01, 1],
      src: require("@/assets/images/map/logo.png"),
      offset: [-2, 0],
      crossOrigin: 'anonymous',
    })
  });
  bottomLeftFeature.setStyle(iconStyle)
  const bottomLeftSource = new ol.VectorSource({
    features: [bottomLeftFeature]
  });
  const bottomLeftLayer = new ol.VectorLayer({
    source: bottomLeftSource
  });
  map.addLayer(bottomLeftLayer)

  // 动态更新图片位置的函数
  function updateImagePosition() {
    const extent = mapview.calculateExtent(map.getSize());
    const bottomLeftCoord = [extent[0], extent[1]]; // 获取左下角坐标
    bottomLeftFeature.getGeometry().setCoordinates(bottomLeftCoord); // 更新图片位置
  }
  // 监听分辨率变化
  mapview.on('change:resolution', updateImagePosition)
  // 监听中心点变化
  mapview.on('change:center', updateImagePosition)
  // 监听全屏变化
  document.addEventListener('fullscreenchange', updateImagePosition)
  // 初始化时也调用一次，确保图片初始位置正确
  updateImagePosition()
  return { view, map }
}
